package com.tcl.aota.admin.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.tcl.aota.admin.dto.ApkDTO;
import com.tcl.aota.admin.dto.ApkReponseDTO;
import com.tcl.aota.admin.dto.ApkVo;
import com.tcl.aota.admin.dto.AppVo;
import com.tcl.aota.admin.dto.CurefParam;
import com.tcl.aota.admin.dto.JsonResult;
import com.tcl.aota.admin.dto.ProductCurefVo;
import com.tcl.aota.admin.dto.Result;
import com.tcl.aota.admin.job.UpFileInstance;
import com.tcl.aota.admin.util.ApkParser;
import com.tcl.aota.admin.util.FileStoreUtil;
import com.tcl.aota.admin.util.RequestUtil;
import com.tcl.aota.admin.util.S3Util;
import com.tcl.aota.common.constants.Constants;
import com.tcl.aota.common.utils.IPUtil;
import com.tcl.aota.common.utils.StringUtil;
import com.tcl.aota.manage.AppManage;
import com.tcl.aota.manage.CurefManage;
import com.tcl.aota.persistent.model.Admin;
import com.tcl.aota.persistent.model.App;
import com.tcl.aota.persistent.model.Curef;

/**
 * @author kelong
 * @date 11/5/14
 */
@Component
public class AppManager {

    private static Logger LOG = Logger.getLogger(AppManager.class);
    @Resource
    private AppManage appManage;
    @Resource(name = "amazons3Manager")
    private Amazons3Manager amazons3Manager;
    @Resource
    private CurefManage curefManage;
    @Value("${thrid.appKeys}")
    private String appKeys;

    /**
     * parse the apk infomation
     *
     * @param uuid
     * @return
     */
    public ApkReponseDTO parseApk(String uuid, HttpServletRequest request) {
        ApkReponseDTO reponseDTO = new ApkReponseDTO();
        try {
            if (uuid == null) {
                //上传本地失败
                LOG.info("app upload failed." + uuid);
                reponseDTO.setResultFlag(Constants.APK.UPLOAD_FAIL);
                return reponseDTO;
            }
            //定义ICON存储路径
            String iconOutPath = FileStoreUtil.getFormalDir(request) + Constants.APK.ICON_PATH;
            File iconDir = new File(iconOutPath);
            if (!iconDir.exists()) {
                iconDir.mkdirs();
            }
            File apkFile = FileStoreUtil.getFileViaUUID(uuid);
            ApkParser parser = new ApkParser();
            ApkDTO apkDTO = parser.apkParse(apkFile.getPath(), iconOutPath);
            if (apkDTO == null || !apkDTO.isValid()) {
                //解析失败
                reponseDTO.setResultFlag(Constants.APK.PARSE_FAIL);
                return reponseDTO;
            }
            //检查是否有相同的 package，versionCode,versionName存在与库中
            Map<String, Object> param = new HashMap();
            param.put("apkPackName", apkDTO.getPackageName());
            param.put("versionCode", apkDTO.getVersionCode());
            param.put("versionName", apkDTO.getVersionName());
            App app = appManage.selectAppsByVersion(param);
            if (app != null) {
                reponseDTO.setResultFlag(Constants.APK.PARSE_EXISTED);
                LOG.info("parse apk success.but exist in DB," + apkDTO.getVersionCode() + ","
                    + apkDTO.getPackageName()
                    + "," + apkDTO.getVersionName());
                return reponseDTO;
            }
            reponseDTO.setApkuuid(uuid);
            reponseDTO.setAppName(apkDTO.getAppName());
            reponseDTO.setVersionName(apkDTO.getVersionName());
            reponseDTO.setVersionCode(apkDTO.getVersionCode());
            reponseDTO.setPackageName(apkDTO.getPackageName());
            reponseDTO.setFileSize(apkDTO.getFileSize());
            reponseDTO.setPermissions(apkDTO.parsePermitions());
            String basePath = FileStoreUtil.getHostAddress(request);
            reponseDTO.setIcon(basePath + Constants.APK.ICON_PATH + apkDTO.getIcon());
            //解析成功
            reponseDTO.setResultFlag(Constants.APK.PARSE_SUCCESS);
            synFile(uuid, Constants.APK.APK_FLAG);//异步上传apk到s3
            //异步上传ICON到
            //ICON，copy to temp dir and syn to s3.
            String icon = apkDTO.getIcon();
            if (!StringUtils.isEmpty(icon)) {
                File file = new File(iconOutPath + apkDTO.getIcon());
                if (file.exists()) {
                    String iconUuid = FileStoreUtil.storeFile(file, file.getName(), 1);
                    reponseDTO.setIconUuid(iconUuid);
                    synFile(iconUuid, Constants.APK.ICON_FLAG);
                }
            }
            LOG.info("parse apk sucess." + uuid);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return reponseDTO;
    }

    /**
     * 上传解析APK
     *
     * @param request
     * @return
     */
    public JsonResult thirdUploadApk(HttpServletRequest request, String appKey) {
        LOG.info("Call Third UploadApk API......");
        List<String> keys = Arrays.asList(appKeys.split(","));
        if (StringUtils.isEmpty(appKey) || keys == null || !keys.contains(appKey)) {
            LOG.info("Access unauthorized.appKey:" + appKey);
            return JsonResult.get(Constants.Common.AUTH_FAIL, "Access unauthorized", null);
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile apkFile = multipartRequest.getFile("apkFile");
        String uuid = FileStoreUtil.storeAPk(apkFile);
        if (uuid == null) {
            LOG.info("Apk upload failed." + uuid);
            return JsonResult.get(Constants.Common.FAIL, "Apk upload or parse failed.", null);
        }
        String iconOutPath = FileStoreUtil.getFormalDir(request) + Constants.APK.ICON_PATH;
        File iconDir = new File(iconOutPath);
        if (!iconDir.exists()) {
            iconDir.mkdirs();
        }
        File file = FileStoreUtil.getFileViaUUID(uuid);
        ApkParser parser = new ApkParser();
        ApkDTO apkDto = parser.apkParse(file.getPath(), iconOutPath);
        if (apkDto == null || !apkDto.isValid()) {
            //解析失败
            LOG.info("Apk parse failed.");
            return JsonResult.get(Constants.Common.FAIL, "Apk upload or parse failed.", null);
        }
        //解析成功，判断packageName和versionCode.
        Map<String, Object> param = new HashMap();
        String apkPackName = apkDto.getPackageName();
        param.put("apkPackName", apkPackName);
        param.put("versionCode", apkDto.getVersionCode());
        param.put("versionName", apkDto.getVersionName());
        App oldApp = appManage.selectAppsByVersion(param);
        if (oldApp != null) {
            LOG.info("Failed,Existing package,versionName,versionCode.package:" + apkPackName
                + ",versionName:"
                + apkDto.getVersionName() + ",versionCode:" + apkDto.getVersionCode());
            return JsonResult.get(Constants.Common.FAIL, "Existing version.", null); //版本已存在或者更低版本
        }
        List<String> appKeys = new ArrayList<String>();
        //异步上传apk到s3
        synFile(uuid, Constants.APK.APK_FLAG);
        //ICON，copy to temp dir and syn to s3.
        String apkPath = Constants.APK.APK_PATH + file.getName();
        appKeys.add(apkPath);
        String icon = apkDto.getIcon();
        String iconPath = "";
        if (!StringUtils.isEmpty(icon)) {
            File iconFile = new File(iconOutPath + icon);
            if (file.exists()) {
                String iconUuid = FileStoreUtil.storeFile(iconFile, iconFile.getName(), 1);
                File imgFile = FileStoreUtil.getFileViaUUID(iconUuid);
                synFile(iconUuid, Constants.APK.ICON_FLAG);
                iconPath = Constants.APK.ICON_PATH + imgFile.getName();
                appKeys.add(iconPath);
            }
        }
        try {
            String resPrefix = S3Util.getResourcePrefix();
            String appUrl = StringUtils.isEmpty(apkPath) ? "" : resPrefix + apkPath;
            String appIcon = StringUtils.isEmpty(iconPath) ? "" : resPrefix + iconPath;
            App app = new App();
            app.setAppName(apkDto.getAppName());
            app.setApkPackName(apkDto.getPackageName());
            app.setAppSize(apkDto.getFileSize());
            app.setVersionCode(apkDto.getVersionCode());
            app.setVersionName(apkDto.getVersionName());
            app.setAppPermission(apkDto.parsePermitions());
            app.setAppUrl(appUrl);//apk S3 path
            app.setAppIcon(appIcon);//icon S3 path
            //新增app
            app.setAppSequence(Constants.Common.DEFAULT_SEQUENCE);
            app.setTrash(Constants.APPStatus.UNTRASH);
            app.setReleaseStatus(Constants.APPStatus.UN_PUBLISH);
            app.setSourceChannel(Constants.APPStatus.DEFAULT_SOURCE);
            app.setAppStartGrade(Constants.APPStatus.DEFAULT_STAR);
            app.setLabel(Constants.APPStatus.DEFAULT_LABEL);
            app.setInstallFlag(Constants.APPStatus.INSTALL_SILENT);
            app.setAppOsVersion(Constants.APPStatus.DEFAULT_OS);
            app.setUploadUser(Constants.APPStatus.DEFAULT_UPLOAD_USER);
            app.setCreateTime(new Date());
            app.setUpdateTime(new Date());
            int num = appManage.insert(app);
            if (num > 0) {
                //success,去除清除上传apk和icon的任务。
                UpFileInstance.getInstance().remove(appKeys);
            }
            LOG.info("Access Third UploadApk API Success,insert App," + num);
            return JsonResult.get(Constants.Common.SUCCESS, "Upload apk success.", convertApp(app));
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return JsonResult.get(Constants.Common.FAIL, "Server error.", null);
        }
    }

    /**
     * covert app to vo
     *
     * @param app
     * @return
     */
    private ApkVo convertApp(App app) {
        if (app == null) {
            return null;
        }
        ApkVo apkVo = new ApkVo();
        apkVo.setApkUrl(app.getAppUrl());
        apkVo.setIconUrl(app.getAppIcon());
        apkVo.setAppName(app.getAppName());
        apkVo.setPackageName(app.getApkPackName());
        apkVo.setVersionCode(app.getVersionCode());
        apkVo.setVersionName(app.getVersionName());
        apkVo.setFileSize(app.getAppSize());
        return apkVo;
    }

    /**
     * sync upload img
     *
     * @param uuid
     */
    public void synFile(String uuid, int type) {
        try {
            File file = FileStoreUtil.getFileViaUUID(uuid);
            if (file.exists()) {
                String descPath = "";
                switch (type) {
                    case Constants.APK.APK_FLAG:
                        descPath = Constants.APK.APK_PATH + file.getName();
                        break;
                    case Constants.APK.ICON_FLAG:
                        descPath = Constants.APK.ICON_PATH + file.getName();
                        break;
                    case Constants.APK.IMAGS_FLAG:
                        descPath = Constants.APK.IMAGS_PATH + file.getName();
                        break;
                }
                if (!StringUtils.isEmpty(descPath)) {
                    amazons3Manager.syncStoreFile(file, descPath);
                    //上传文件标记
                    UpFileInstance.getInstance().put(descPath);
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * insert app
     *
     * @param appVo
     * @return
     */
    public int insertApp(AppVo appVo, HttpServletRequest request) {
        int status = Constants.Common.FAIL;
        String iconPath = "";
        try {
            Admin admin = RequestUtil.getSessionUser(request);
            List<String> appKeys = new ArrayList<String>();
            String resPrefix = S3Util.getResourcePrefix();
            //store icon
            File iconFile = FileStoreUtil.getFileViaUUID(appVo.getAppIconUUID());
            if (iconFile != null) {
                iconPath = Constants.APK.ICON_PATH + iconFile.getName();
                appKeys.add(iconPath);
            }
            //store apk
            File apkFile = FileStoreUtil.getFileViaUUID(appVo.getAppUrlUUID());
            String apkPath = "";
            if (apkFile != null) {
                apkPath = Constants.APK.APK_PATH + apkFile.getName();
                appKeys.add(apkPath);
            }
            //store imgs
            String imgs = appVo.getAppImgUUIDs();
            String[] imgsArray = imgs.split(",");
            StringBuilder imgsSb = new StringBuilder();
            if (imgsArray != null && imgsArray.length > 0) {
                for (String imgUuid : imgsArray) {
                    File imgFile = FileStoreUtil.getFileViaUUID(imgUuid);
                    if (imgFile != null) {
                        String imgPath = Constants.APK.IMAGS_PATH + imgFile.getName();
                        imgsSb.append(resPrefix + imgPath + ",");
                        appKeys.add(imgPath);
                    }
                }
                if (imgsSb.length() > 0) {
                    imgsSb = imgsSb.delete(imgsSb.length() - 1, imgsSb.length());
                }
            }
            App app = new App();
            app.setAppName(StringUtils.isEmpty(appVo.getAppName()) ? null : appVo.getAppName());
            app.setApkPackName(appVo.getApkPackName());
            app.setAppSize(appVo.getAppSize());
            app.setAppStartGrade(appVo.getAppStartGrade());
            app.setAppDeveloper(appVo.getAppDeveloper());
            app.setAppDetail(appVo.getAppDetail());
            app.setAppPermission(appVo.getAppPermission());
            app.setSourceChannel(appVo.getSourceChannel());
            app.setVersionName(appVo.getVersionName());
            app.setVersionCode(appVo.getVersionCode());
            app.setAppUrl(StringUtils.isEmpty(apkPath) ? "" : resPrefix + apkPath);//apk S3 path
            app.setAppIcon(StringUtils.isEmpty(iconPath) ? "" : resPrefix + iconPath);//icon S3 path
            app.setAppImgs(imgsSb.toString());//imgs S3 path
            app.setAppSequence(Constants.Common.DEFAULT_SEQUENCE);
            app.setAppOsVersion(appVo.getAppOsVersion());
            app.setLabel(appVo.getLabel());
            app.setTrash(Constants.APPStatus.UNTRASH);
            app.setReleaseStatus(Constants.APPStatus.UN_PUBLISH);
            app.setCreateTime(new Date());
            app.setUpdateTime(new Date());
            app.setInstallFlag(appVo.getInstallFlag());
            app.setUploadUser(admin.getAdminName());//上传人
            int result = appManage.insert(app);
            if (result > 0) {
                //success
                UpFileInstance.getInstance().remove(appKeys);
            }
            LOG.info("add app success." + app.getAppName());
            status = Constants.Common.SUCCESS;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return status;
    }

    /**
     * 编辑app信息
     *
     * @param appVo:app Vo对象
     * @return
     */
    public int updateApp(AppVo appVo) {
        int status = Constants.Common.FAIL;
        try {
            App oldApp = appManage.selectById(appVo.getId());
            //只能编辑同package的APP
            if (!appVo.getApkPackName().equals(oldApp.getApkPackName())) {
                return Constants.Common.PKG_NOT_SAME;
            }
            List<String> appKeys = new ArrayList<String>();
            String resPrefix = S3Util.getResourcePrefix();
            //检测apk,icon,images是否重新上传，整理路径
            String apkPath = appVo.getAppUrlUUID();
            String iconPath = appVo.getAppIconUUID();
            String imgsPath = appVo.getAppImgUUIDs();
            //从新上传的apk
            boolean apkUpdateFlag = false;//标记apk路径是否更新
            boolean iconUpdateFlag = false;//标记icon路径是否更新
            boolean imgsUpdateFlag = false;//标记imgs是否更新
            //icon从新上传
            if (StringUtils.isEmpty(apkPath)) {
                return Constants.Common.PARAMS_INVALID;
            }
            if (apkPath.indexOf(resPrefix) == -1) {
                File apkFile = FileStoreUtil.getFileViaUUID(appVo.getAppUrlUUID());
                if (apkFile != null) {
                    apkPath = Constants.APK.APK_PATH + apkFile.getName();
                    appKeys.add(apkPath);
                    appVo.setAppUrlUUID(resPrefix + apkPath);
                    //apk重新上传，则更新成功后删除原来s3路径的apk
                    apkUpdateFlag = true;
                }
            }
            //icon从新上传
            if (StringUtils.isEmpty(iconPath)) {
                return Constants.Common.PARAMS_INVALID;
            }
            if (iconPath.indexOf(resPrefix) == -1) {
                File iconFile = FileStoreUtil.getFileViaUUID(appVo.getAppIconUUID());
                if (iconFile != null) {
                    iconPath = Constants.APK.ICON_PATH + iconFile.getName();
                    appKeys.add(iconPath);
                    appVo.setAppIconUUID(resPrefix + iconPath);
                    iconUpdateFlag = true;
                }
            }
            String[] imgsArray = imgsPath.split(",");
            if (imgsArray == null || imgsArray.length == 0) {
                return Constants.Common.PARAMS_INVALID;
            }
            StringBuilder imgsSb = new StringBuilder();
            for (String imgUuid : imgsArray) {
                if (imgUuid.indexOf(resPrefix) == -1) {
                    File imgFile = FileStoreUtil.getFileViaUUID(imgUuid);
                    if (imgFile != null) {
                        String imgPath = Constants.APK.IMAGS_PATH + imgFile.getName();
                        imgsSb.append(resPrefix + imgPath + ",");
                        appKeys.add(imgPath);
                        if (!imgsUpdateFlag) {
                            imgsUpdateFlag = true;
                        }
                    }
                } else {
                    imgsSb.append(imgUuid + ",");//直接拼装
                }
            }
            if (imgsSb.length() > 0) {
                imgsSb = imgsSb.delete(imgsSb.length() - 1, imgsSb.length());
            }
            App app = new App();
            app.setId(appVo.getId());
            app.setAppName(StringUtils.isEmpty(appVo.getAppName()) ? null : appVo.getAppName());
            app.setApkPackName(appVo.getApkPackName());
            app.setAppSize(appVo.getAppSize());
            app.setAppStartGrade(appVo.getAppStartGrade());
            app.setAppDeveloper(appVo.getAppDeveloper());
            app.setAppDetail(appVo.getAppDetail());
            app.setAppPermission(appVo.getAppPermission());
            app.setSourceChannel(appVo.getSourceChannel());
            app.setVersionName(appVo.getVersionName());
            app.setVersionCode(appVo.getVersionCode());
            app.setAppUrl(appVo.getAppUrlUUID());//apk S3 path
            app.setAppIcon(appVo.getAppIconUUID());//icon S3 path
            app.setAppImgs(imgsSb.toString());//imgs S3 path
            app.setUpdateTime(new Date());
            app.setLabel(appVo.getLabel());
            app.setAppOsVersion(appVo.getAppOsVersion());
            app.setTrash(Constants.APPStatus.UNTRASH);
            app.setInstallFlag(appVo.getInstallFlag());
            int result = appManage.update(app);
            if (result > 0) {
                //success
                UpFileInstance.getInstance().remove(appKeys);
                //s3删除已更新的文件
                List<String> delFiles = new ArrayList<>();
                int prefixSize = resPrefix.length();
                if (apkUpdateFlag) {
                    String oldApkPath = oldApp.getAppUrl();
                    delFiles.add(oldApkPath.substring(prefixSize));
                }
                if (iconUpdateFlag) {
                    String oldIconPath = oldApp.getAppIcon();
                    delFiles.add(oldIconPath.substring(prefixSize));
                }
                if (imgsUpdateFlag) {
                    List<String> oldImgList = StringUtil.strToList(oldApp.getAppImgs());
                    List<String> newImgList = StringUtil.strToList(app.getAppImgs());
                    if (oldImgList != null && newImgList != null) {
                        for (String oldImg : oldImgList) {
                            if (!newImgList.contains(oldImg)) {
                                delFiles.add(oldImg);
                            }
                        }
                    }
                }
                amazons3Manager.syncDelFiles(delFiles);
            }
            LOG.info("edit app success." + app.getAppName());
            status = Constants.Common.SUCCESS;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return status;
    }

    /**
     * delete app from DB and delete files from amazon S3
     *
     * @param ids
     * @return
     */
    public int deleteApps(List<Long> ids) {
        List<App> apps = new ArrayList<App>();
        for (Long id : ids) {
            App app = appManage.selectById(id);
            if (app != null) {
                apps.add(app);
            }
        }
        int result = appManage.deleteApps(ids);
        //delete files from s3
        if (result > 0) {
            //删除成功
            String resPrefix = S3Util.getResourcePrefix();
            int prefixSize = resPrefix.length();
            List<String> filePaths = new ArrayList<String>();
            for (App app : apps) {
                try {
                    String appUrl = app.getAppUrl();
                    String appIcon = app.getAppIcon();
                    String appImgs = app.getAppImgs();
                    if (!StringUtils.isEmpty(appUrl)) {
                        if (appUrl.indexOf(resPrefix) != -1)
                            filePaths.add(appUrl.substring(prefixSize));//apk
                    }
                    if (!StringUtils.isEmpty(appIcon)) {
                        if (appIcon.indexOf(resPrefix) != -1)
                            filePaths.add(appIcon.substring(prefixSize));
                    }
                    if (!StringUtils.isEmpty(appImgs)) {
                        String[] appImgArr = appImgs.split(",");
                        if (appImgArr != null) {
                            for (String appImg : appImgArr) {
                                if (appImg.indexOf(resPrefix) != -1)
                                    filePaths.add(appImg.substring(prefixSize));
                            }
                        }
                    }
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                }
            }
            amazons3Manager.syncDelFiles(filePaths);
        }
        return result;
    }

    /**
     * publish apps to curefs
     *
     * @param curefParam
     * @return
     */
    public Result publishApp(CurefParam curefParam, HttpServletRequest request) {
        if (curefParam == null || !curefParam.available()) {
            return Result.getResult(Constants.Common.PARAMS_INVALID, "Publish param error.");
        }
        try {
            String ip = IPUtil.getIpAddr(request);
            Admin admin = RequestUtil.getSessionUser(request);

            List<String> curefs = curefParam.getCurefs();
            List<Long> appIds = curefParam.getAppIds();
            appManage.publishApp(appIds, curefs, ip, admin.getAdminName());
            //发布状态，判断发布原因提示
            boolean flag = false;
            for (Long appId : appIds) {
                App app = appManage.selectByPrimaryKey(appId);
                if (app.getReleaseStatus() == Constants.APPStatus.UN_PUBLISH) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                if (appIds.size() == 1) {
                    return Result.getResult(Constants.Common.FAIL,
                        "Publish failed. Higher version already published,please check.");
                } else {
                    return Result.getResult(Constants.Common.SUCCESS,
                        "Some APP publish failed. Higher version already published. please check.");
                }
            }
            return Result.getResult(Constants.Common.SUCCESS, "Publish success.");
            //部分或者全部发布失败
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return Result.getResult(Constants.Common.FAIL, "Publish failed.");
        }
    }

    /**
     * upPublish apps to curefs
     *
     * @param appIds
     * @return
     */
    public Result unPublishApp(List<Long> appIds, HttpServletRequest request) {
        if (appIds == null || appIds.size() == 0) {
            LOG.info("Unpublish app param error");
            return Result.get(null, Constants.Common.PARAMS_INVALID);
        }
        int result = Constants.Common.FAIL;
        String ip = IPUtil.getIpAddr(request);
        Admin admin = RequestUtil.getSessionUser(request);
        try {
            appManage.unPublishApp(appIds, ip, admin.getAdminName());
            LOG.info("Unpublish App Success,appIds:" + appIds + ",Unpublish User:"
                + admin.getAdminName());
            result = Constants.Common.SUCCESS;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        return Result.get(null, result);
    }

    /**
     * get curefs by appId
     *
     * @param appId
     * @return
     */
    public Result appCuref(Long appId) {
        List<Curef> curefs = curefManage.selectCurefByApp(appId);
        if (curefs == null) {
            return Result.get(null, Constants.Common.SUCCESS);
        }
        List<ProductCurefVo> pcvs = buildPcv(curefs);
        return Result.get(pcvs, Constants.Common.SUCCESS);
    }

    /**
     * 所有product和curef列表
     *
     * @param
     * @return
     */
    public Result productCuref(int flag) {
        List<Curef> curefs = curefManage.selectAllCuref(flag);
        if (curefs == null) {
            return Result.get(null, Constants.Common.SUCCESS);
        }
        List<ProductCurefVo> pcvs = buildPcv(curefs);
        return Result.get(pcvs, Constants.Common.SUCCESS);
    }

    public List<ProductCurefVo> buildPcv(List<Curef> curefs) {
        List<ProductCurefVo> pcvs = new ArrayList<>();
        Map<String, List<String>> pcsMap = new HashMap<>();
        for (Curef curef : curefs) {
            String productName = curef.getProduct();
            String curefName = curef.getCuref();
            List<String> pcs = pcsMap.get(productName);
            if (pcs == null) {
                pcs = new ArrayList<>();
                pcs.add(curefName);
                pcsMap.put(productName, pcs);
            } else {
                pcs.add(curefName);
            }
        }
        for (Map.Entry<String, List<String>> entry : pcsMap.entrySet()) {
            ProductCurefVo pcv = new ProductCurefVo();
            pcv.setProduct(entry.getKey());
            pcv.setCurefs(entry.getValue());
            pcvs.add(pcv);
        }
        return pcvs;
    }


}
